﻿// -----------------------------------------------------------------------
// <copyright file="PapMessageReader.cs" company="Zen Design Corp">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Zen.BlackBerry.Pap.Parser
{
	using System;
	using System.IO;
	using System.Xml;
	using System.Xml.Serialization;

	/// <summary>
	/// Responsible for parsing PAP XML messages into managed objects.
	/// </summary>
	public static class PapMessageParser
	{
		/// <summary>
		/// Reads the PAP message from the specified stream.
		/// </summary>
		/// <param name="stream">The stream.</param>
		/// <returns></returns>
		public static PapMessage Read(Stream stream)
		{
			XmlReaderSettings settings =
				new XmlReaderSettings
				{
					CheckCharacters = true,
					CloseInput = true,
					ConformanceLevel = System.Xml.ConformanceLevel.Document,
					DtdProcessing = DtdProcessing.Parse,
					IgnoreComments = true,
					ValidationType = ValidationType.DTD
				};
			XmlReader reader = XmlReader.Create(stream, settings);
			try
			{
				// Deserialize the data
				Type[] extraTypes = new Type[] { typeof(BpdsRoot) };
				XmlSerializer serializer = new XmlSerializer(typeof(PapRoot), extraTypes);
				object resultRoot = serializer.Deserialize(reader);

				// Extract the response object from the appropriate root
				PapMessage response = null;
				if (resultRoot is PapRoot)
				{
					response = ((PapRoot)resultRoot).Response;
				}
				else if (resultRoot is BpdsRoot)
				{
					response = ((BpdsRoot)resultRoot).Response;
				}

				// Check for a BadMessageResponse and throw if encountered
				BadMessageResponse badMessage = response as BadMessageResponse;
				if (badMessage != null)
				{
					throw new BadMessageException(badMessage);
				}

				return response;
			}
			finally
			{
				reader.Close();
			}
		}
	}
}
